package com.liuhuanss.voiceprint.controller;

import com.liuhuanss.voiceprint.dto.ApiResponse;
import com.liuhuanss.voiceprint.service.VoiceprintService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 声纹识别控制器
 * 
 * @author liuhuanss
 * @version 1.0
 */
@RestController
@RequestMapping("/api/voiceprint")
@CrossOrigin(origins = "*")
@Slf4j
public class VoiceprintController {

    @Autowired
    private VoiceprintService voiceprintService;

    /**
     * 创建声纹特征库
     * 
     * @param groupId 组ID
     * @return 创建结果
     */
    @PostMapping("/group/create")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createGroup(@RequestParam("groupId") String groupId) {
        try {
            log.info("收到创建声纹特征库请求，组ID: {}", groupId);
            
            if (groupId == null || groupId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("组ID不能为空", "INVALID_GROUP_ID")
                );
            }
            Map<String, Object> result = voiceprintService.createFeatureGroup(groupId.trim());
            return ResponseEntity.ok(ApiResponse.success("创建声纹特征库成功", result));
        } catch (Exception e) {
            log.error("创建声纹特征库失败", e);
            return ResponseEntity.badRequest().body(
                ApiResponse.error(e.getMessage(), "CREATE_GROUP_FAILED")
            );
        }
    }

    /**
     * 添加声纹特征（文件上传）
     * 
     * @param groupId 组ID
     * @param featureId 特征ID
     * @param featureInfo 特征信息
     * @param audioFile 音频文件
     * @return 添加结果
     */
    @PostMapping("/feature/add")
    public ResponseEntity<ApiResponse<Map<String, Object>>> addFeature(
            @RequestParam("groupId") String groupId,
            @RequestParam("featureId") String featureId,
            @RequestParam(value = "featureInfo", required = false, defaultValue = "") String featureInfo,
            @RequestParam("audioFile") MultipartFile audioFile) {
        try {
            log.info("收到添加声纹特征请求，组ID: {}, 特征ID: {}, 文件: {}", 
                    groupId, featureId, audioFile.getOriginalFilename());
            
            // 参数验证
            if (groupId == null || groupId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("组ID不能为空", "INVALID_GROUP_ID")
                );
            }
            
            if (featureId == null || featureId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("特征ID不能为空", "INVALID_FEATURE_ID")
                );
            }
            
            if (audioFile == null || audioFile.isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("音频文件不能为空", "INVALID_AUDIO_FILE")
                );
            }
            
            Map<String, Object> result = voiceprintService.addAudioFeature(
                groupId.trim(), 
                featureId.trim(), 
                featureInfo.trim(), 
                audioFile
            );
            
            return ResponseEntity.ok(ApiResponse.success("添加声纹特征成功", result));
        } catch (Exception e) {
            log.error("添加声纹特征失败", e);
            return ResponseEntity.badRequest().body(
                ApiResponse.error(e.getMessage(), "ADD_FEATURE_FAILED")
            );
        }
    }

    /**
     * 添加声纹特征（Base64数据）
     * 
     * @param request 请求参数
     * @return 添加结果
     */
    @PostMapping("/feature/add-base64")
    public ResponseEntity<ApiResponse<Map<String, Object>>> addFeatureBase64(
            @RequestBody AddFeatureRequest request) {
        try {
            log.info("收到添加声纹特征请求（Base64），组ID: {}, 特征ID: {}", 
                    request.getGroupId(), request.getFeatureId());
            
            // 参数验证
            if (request.getGroupId() == null || request.getGroupId().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("组ID不能为空", "INVALID_GROUP_ID")
                );
            }
            
            if (request.getFeatureId() == null || request.getFeatureId().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("特征ID不能为空", "INVALID_FEATURE_ID")
                );
            }
            
            if (request.getAudioBase64() == null || request.getAudioBase64().trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("音频数据不能为空", "INVALID_AUDIO_DATA")
                );
            }
            
            Map<String, Object> result = voiceprintService.addAudioFeature(
                request.getGroupId().trim(), 
                request.getFeatureId().trim(), 
                request.getFeatureInfo() != null ? request.getFeatureInfo().trim() : "", 
                request.getAudioBase64().trim()
            );
            
            return ResponseEntity.ok(ApiResponse.success("添加声纹特征成功", result));
        } catch (Exception e) {
            log.error("添加声纹特征失败（Base64）", e);
            return ResponseEntity.badRequest().body(
                ApiResponse.error(e.getMessage(), "ADD_FEATURE_FAILED")
            );
        }
    }

    /**
     * 1:1声纹比对（文件上传）
     * 
     * @param groupId 组ID
     * @param featureId 特征ID
     * @param audioFile 音频文件
     * @return 比对结果
     */
    @PostMapping("/compare/one-to-one")
    public ResponseEntity<ApiResponse<Map<String, Object>>> compareOneToOne(
            @RequestParam("groupId") String groupId,
            @RequestParam("featureId") String featureId,
            @RequestParam("audioFile") MultipartFile audioFile) {
        try {
            log.info("收到1:1声纹比对请求，组ID: {}, 特征ID: {}, 文件: {}", 
                    groupId, featureId, audioFile.getOriginalFilename());
            
            // 参数验证
            if (groupId == null || groupId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("组ID不能为空", "INVALID_GROUP_ID")
                );
            }
            
            if (featureId == null || featureId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("特征ID不能为空", "INVALID_FEATURE_ID")
                );
            }
            
            if (audioFile == null || audioFile.isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("音频文件不能为空", "INVALID_AUDIO_FILE")
                );
            }
            
            Map<String, Object> result = voiceprintService.searchOneFeature(
                groupId.trim(), 
                featureId.trim(), 
                audioFile
            );
            
            return ResponseEntity.ok(ApiResponse.success("1:1声纹比对完成", result));
        } catch (Exception e) {
            log.error("1:1声纹比对失败", e);
            return ResponseEntity.badRequest().body(
                ApiResponse.error(e.getMessage(), "COMPARE_ONE_TO_ONE_FAILED")
            );
        }
    }

    /**
     * 1:N声纹比对（文件上传）
     * 
     * @param groupId 组ID
     * @param audioFile 音频文件
     * @return 比对结果
     */
    @PostMapping("/compare/one-to-many")
    public ResponseEntity<ApiResponse<Map<String, Object>>> compareOneToMany(
            @RequestParam("groupId") String groupId,
            @RequestParam("audioFile") MultipartFile audioFile) {
        try {
            log.info("收到1:N声纹比对请求，组ID: {}, 文件: {}", 
                    groupId, audioFile.getOriginalFilename());
            
            // 参数验证
            if (groupId == null || groupId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("组ID不能为空", "INVALID_GROUP_ID")
                );
            }
            
            if (audioFile == null || audioFile.isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("音频文件不能为空", "INVALID_AUDIO_FILE")
                );
            }
            
            Map<String, Object> result = voiceprintService.searchFeature(
                groupId.trim(), 
                audioFile
            );
            
            return ResponseEntity.ok(ApiResponse.success("1:N声纹比对完成", result));
        } catch (Exception e) {
            log.error("1:N声纹比对失败", e);
            return ResponseEntity.badRequest().body(
                ApiResponse.error(e.getMessage(), "COMPARE_ONE_TO_MANY_FAILED")
            );
        }
    }

    /**
     * 删除声纹特征
     * 
     * @param groupId 组ID
     * @param featureId 特征ID
     * @return 删除结果
     */
    @DeleteMapping("/feature/delete")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteFeature(
            @RequestParam("groupId") String groupId,
            @RequestParam("featureId") String featureId) {
        try {
            log.info("收到删除声纹特征请求，组ID: {}, 特征ID: {}", groupId, featureId);
            
            // 参数验证
            if (groupId == null || groupId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("组ID不能为空", "INVALID_GROUP_ID")
                );
            }
            
            if (featureId == null || featureId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("特征ID不能为空", "INVALID_FEATURE_ID")
                );
            }
            
            Map<String, Object> result = voiceprintService.deleteFeature(
                groupId.trim(), 
                featureId.trim()
            );
            
            return ResponseEntity.ok(ApiResponse.success("删除声纹特征成功", result));
        } catch (Exception e) {
            log.error("删除声纹特征失败", e);
            return ResponseEntity.badRequest().body(
                ApiResponse.error(e.getMessage(), "DELETE_FEATURE_FAILED")
            );
        }
    }

    /**
     * 添加特征请求DTO
     */
    public static class AddFeatureRequest {
        private String groupId;
        private String featureId;
        private String featureInfo;
        private String audioBase64;

        // Getters and Setters
        public String getGroupId() {
            return groupId;
        }

        public void setGroupId(String groupId) {
            this.groupId = groupId;
        }

        public String getFeatureId() {
            return featureId;
        }

        public void setFeatureId(String featureId) {
            this.featureId = featureId;
        }

        public String getFeatureInfo() {
            return featureInfo;
        }

        public void setFeatureInfo(String featureInfo) {
            this.featureInfo = featureInfo;
        }

        public String getAudioBase64() {
            return audioBase64;
        }

        public void setAudioBase64(String audioBase64) {
            this.audioBase64 = audioBase64;
        }
    }
}